package org.nightstudio.common.util.action;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.nightstudio.common.face.action.spi.NightStudioAction;
import org.springframework.web.bind.annotation.RequestMapping;

public class ActionUtil {
	private static Logger logger = Logger.getLogger(ActionUtil.class);
	private static Map<Class<? extends NightStudioAction>, String> actionPathMap = new HashMap<Class<? extends NightStudioAction>, String>();
	
	public static String getContextPath(HttpServletRequest request) {
		return request.getContextPath();
	}
	public static String getSessionErrorAction(HttpServletRequest request) {
		return getContextPath(request) + "/sessionError.do";
	}
	public static String getActionPath(HttpServletRequest request, Class<? extends NightStudioAction> clazz) {
		if (actionPathMap.get(clazz) == null) {
			Annotation[] annotations = clazz.getAnnotations();
			for (Annotation annotation : annotations) {
				if (annotation.annotationType().equals(RequestMapping.class)) {
					RequestMapping mapping = (RequestMapping) annotation;
					String[] values = mapping.value();
					if (values != null && values[0] != null) {
						for (String value : values) {
							if (value.endsWith(".do")) {
								actionPathMap.put(clazz, value);
							}
						}
					}
				}
			}
		}
		String path;
		if ((path = actionPathMap.get(clazz)) == null) {
			logger.warn("could not get path for action '" + clazz.getName() + "'");
			return "";
		} else {
			return getContextPath(request) + path;
		}
	}
}
